package com.mq.consumer.simple;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;

/**
 * @Classname KafkaSimpleConsumer
 * @Description
 * @Version 1.0.0
 * @Date 2024/12/4 17:15
 * @Created by ncs
 */
public class KafkaSimpleConsumerOffSet {

    public static void main(String[] args) {
        //1. 创建消费者对象  需要范型 k,v
        // 1.1 配置对象
        HashMap<String, Object> configMap = new HashMap<>();
        configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.125.100:9093");
        // 1.2 序列化
        configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //从头开始消费
        configMap.put(ConsumerConfig.GROUP_ID_CONFIG, "czp2");
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(configMap);
        //2. 订阅主题
        kafkaConsumer.subscribe(Collections.singleton("czp_topic"));
        //获取集群信息
        boolean flag = true;
        while (flag){
            kafkaConsumer.poll(Duration.ofMillis(100));
            Set<TopicPartition> assignment = kafkaConsumer.assignment();
            if(null != assignment && !assignment.isEmpty()){
                for (TopicPartition topicPartition: assignment){
                    if("czp_topic".equals(topicPartition.topic())){
                        kafkaConsumer.seek(topicPartition, 5);
                        flag = false;
                    }
                }
            }
        }
        //3. 拉取数据
        while (true){
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
            records.forEach(item->{
                System.out.println(item);
            });
        }
        // 4. 关闭连接
       // kafkaConsumer.close();
    }
}
